package com.system.realm;

import com.system.pojo.UserLogin;
import com.system.server.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

/**
 * @Author: E-mail:
 * @Version: 创建时间：2019年04月20日20:57
 * @Description: <描述>
 */
public class UserInfoRealm extends AuthorizingRealm {
    @Autowired
    private UserService userService;
    /**
     * 授权
     * @param principal
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        //得到用户名
        String userName = (String) principal.getPrimaryPrincipal();
        //获取用户的角色
        Set<String> roles = userService.findRolesByName(userName);

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        info.addRoles(roles);
        return info;
    }
    /**
     * 认证
     * @param token
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //得到用户
        String loginName = (String)token.getPrincipal();

        UserLogin userLogin = userService.findUserLoginByName(loginName);

        //判断用户是否存在
        if(userLogin == null) {
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(
                loginName,
                userLogin.getPassword(),
                getName()
        );
    }
}
